// pages/bank-detail/bank-detail.js
const app = getApp()

// 常量定义
const CONSTANTS = {
    STORAGE_KEY: 'answerHistory',
    ERROR_DELAY: 1500,
    DIFFICULTY_MAP: {
        '简单': 'easy',
        '中等': 'medium',
        '困难': 'hard',
        'easy': 'easy',
        'medium': 'medium',
        'hard': 'hard'
    }
}

Page({
    /**
     * 页面的初始数据
     */
    data: {
        bankId: null,
        bankInfo: null,
        questions: [],
        stats: {
            totalQuestions: 0,
            completedCount: 0,
            correctRate: 0
        },
        isLoading: true,
        // 缓存答题历史，避免频繁读取存储
        answerHistory: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const {id} = options
        if (id) {
            this.setData({bankId: parseInt(id)})
            this.loadBankDetail()
        } else {
            this.showErrorAndGoBack('参数错误')
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.loadBankDetail()
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        const {bankInfo} = this.data
        return {
            title: `${bankInfo?.name || '题库'} - 来挑战一下吧！`,
            path: `/pages/bank-detail/bank-detail?id=${this.data.bankId}`
        }
    },

    // ==================== 数据处理方法 ====================

    /**
     * 加载题库详情
     */
    loadBankDetail() {
        const {bankId} = this.data
        const questionBanks = app.globalData.questionBanks
        const allQuestions = app.globalData.questionBank

        // 找到对应题库
        const bankInfo = questionBanks.find(bank => bank.id === bankId)
        if (!bankInfo) {
            this.showErrorAndGoBack('题库不存在')
            return
        }

        // 获取题库中的题目
        const questions = allQuestions.filter(q =>
            bankInfo.questionIds.includes(q.id)
        )

        // 缓存答题历史，避免频繁读取存储
        const answerHistory = wx.getStorageSync(CONSTANTS.STORAGE_KEY) || []
        const bankHistory = answerHistory.filter(h =>
            questions.some(q => q.id === h.questionId)
        )

        // 计算统计数据
        const stats = this.calculateStats(questions, bankHistory)

        this.setData({
            bankInfo,
            questions,
            stats,
            answerHistory, // 缓存答题历史
            isLoading: false
        })

        // 设置页面标题
        wx.setNavigationBarTitle({
            title: bankInfo.name
        })
    },

    /**
     * 计算统计数据
     */
    calculateStats(questions, bankHistory) {
        const completedCount = new Set(bankHistory.map(h => h.questionId)).size
        const correctCount = bankHistory.filter(h => h.isCorrect).length
        const correctRate = bankHistory.length > 0 ?
            Math.round((correctCount / bankHistory.length) * 100) : 0

        return {
            totalQuestions: questions.length,
            completedCount,
            correctRate
        }
    },

    // ==================== 事件处理方法 ====================

    /**
     * 开始答题
     */
    startQuiz() {
        const {questions} = this.data
        if (questions.length === 0) {
            wx.showToast({
                title: '暂无题目',
                icon: 'none'
            })
            return
        }

        // 跳转到第一题
        const firstQuestion = questions[0]
        this.navigateToQuestion(firstQuestion.id)
    },

    /**
     * 继续答题（跳转到未完成的题目）
     */
    continueQuiz() {
        const {questions, answerHistory} = this.data

        // 找到第一个未答的题目
        const uncompletedQuestion = questions.find(q =>
            !answerHistory.some(h => h.questionId === q.id)
        )

        if (uncompletedQuestion) {
            this.navigateToQuestion(uncompletedQuestion.id)
        } else {
            // 所有题目都已完成，从第一题开始
            this.startQuiz()
        }
    },

    /**
     * 跳转到具体题目
     */
    goToQuestion(e) {
        const {id} = e.currentTarget.dataset
        this.navigateToQuestion(id)
    },

    // ==================== 工具方法 ====================

    /**
     * 难度等级映射
     */
    getDifficultyClass(difficulty) {
        return CONSTANTS.DIFFICULTY_MAP[difficulty] || 'medium'
    },

    /**
     * 检查题目是否已完成
     */
    isQuestionCompleted(questionId) {
        const {answerHistory} = this.data
        return answerHistory.some(h => h.questionId === questionId)
    },

    /**
     * 检查题目是否答对
     */
    isQuestionCorrect(questionId) {
        const {answerHistory} = this.data
        const record = answerHistory.find(h => h.questionId === questionId)
        return record ? record.isCorrect : false
    },

    /**
     * 统一的页面跳转方法
     */
    navigateToQuestion(questionId) {
        wx.navigateTo({
            url: `/pages/question-detail/question-detail?bankId=${this.data.bankId}&questionId=${questionId}`
        })
    },

    /**
     * 统一的错误处理方法
     */
    showErrorAndGoBack(message) {
        wx.showToast({
            title: message,
            icon: 'error'
        })
        setTimeout(() => {
            wx.navigateBack()
        }, CONSTANTS.ERROR_DELAY)
    }
})